<script setup>
    import {reactive, ref, computed, watchEffect, watch} from 'vue'
    import {Delete, Minus, Plus} from "@element-plus/icons-vue";
    import {ElMessage, ElMessageBox} from "element-plus";
    import {cartListService, cartUpdateService, cartDeleteService} from "@/api/shoppingcart";
    import request from "@/utils/request";
    // 店铺
    const suppliers = ref([]);
    //购物车列表
    const cartList = async () => {
        let result = await cartListService();
        console.log('购物车中内容为：')
        console.log(result.data)
        if (result.data != null) {
            const groupedData = {};
            result.data.forEach(item => {
                if (!groupedData[item.s_id]) {
                    groupedData[item.s_id] = {
                        s_id: item.s_id,
                        s_username: item.s_nickname,
                        allItemsSelected: false,
                        items: []
                    };
                }
                const newItem = {
                    //放一些数据
                    g_id: item.g_id,
                    g_name: item.g_name,
                    g_unitPrice: item.g_unitprice,
                    g_count: item.g_count,
                    g_img: item.g_img,
                    g_details: item.g_details,
                    selected: false,
                    total: 0
                };
                //将新项目添加到对应的s_id的组中
                groupedData[item.s_id].items.push(newItem);
            });
            console.log('groupedData:')
            console.log(groupedData)

            Object.keys(groupedData).forEach(s_id => {
                suppliers.value.push(groupedData[s_id]);
            })
            console.log('suppliers：')
            console.log(suppliers.value)
        }
    }
    cartList()

    const OrderGoods = reactive([])
    // 选中商品信息checkbox也就是选择购物车中所有项
    const allItemsSelected = ref(false);

    //方法选中或取消选中所有商品
    function toggleAllItems() {
        // 改变checkbox状态
        allItemsSelected.value = !allItemsSelected.value;
        suppliers.value.forEach(supplier => {
            supplier.allItemsSelected = allItemsSelected.value;
            supplier.items.forEach(item => {
                item.selected = allItemsSelected.value;
            });
        });
    }

    // 检查是不是所有商品被选中
    function checkAllItemsSelected() {
        allItemsSelected.value = suppliers.value.every(supplier => supplier.allItemsSelected);
    }

    // 监听suppliers的变化，确保全选状态一致
    watch(suppliers, () => {
        checkAllItemsSelected();
    }, {deep: true});
    // 初始化时检查全选状态
    watchEffect(() => {
        checkAllItemsSelected();
    });

    // 选中店铺中所有商品
    const selectAllSupplierItems = (supplier) => {
        supplier.allItemsSelected = !supplier.allItemsSelected;
        supplier.items.forEach(item => (item.selected = supplier.allItemsSelected));
        let allSelected = true;
        suppliers.value.forEach(s => {
            if (!s.allItemsSelected) {
                allSelected = false;
                return;//如果有任何供应商没有全选，则不会继续检查
            }
        })
        allItemsSelected.value = allSelected;
        updateSupplierTotal(supplier);
    }
    // 更新店铺中选中的单个商品
    const updateItemSelection = (supplier, item) => {
        item.selected = !item.selected;
        // 如果所有商品被选中
        supplier.allItemsSelected = supplier.items.every(i => i.selected);
        checkAllItemsSelected();
        updateSupplierTotal(supplier);
    };
    // 更新店铺总金额
    const updateSupplierTotal = (supplier) => {
        supplier.items.forEach(item => (item.total = item.g_unitPrice * item.g_count));
        supplier.total = supplier.items.reduce((total, item) => (item.selected ? total + item.total : total), 0);
    };

    //店铺金额小计
    const calculateSupplierTotal = (supplier) => {
        return supplier.items.reduce((total, item) => (item.selected ? total + item.total : total), 0);
    };
    // 所有店铺总金额
    const grandTotal = computed(() => {
        if (allItemsSelected) {
            let sum = 0;
            suppliers.value.forEach(supplier => {
                supplier.items.forEach(item => {
                    if (item.selected) {
                        sum += item.g_unitPrice * item.g_count;
                    }
                });
            })
            return sum;
        } else {
            return suppliers.value.reduce((total, supplier) => total + supplier.total, 0);
        }
    });
    suppliers.value.forEach(updateSupplierTotal);
    //计算购物车中商品总数
    const countCart = computed(() => {
        let cartCount = 0;
        suppliers.value.forEach(supplier => {
            supplier.items.forEach(item => {
                cartCount += item.g_count;
            });
        })
        return cartCount;
    })
    //计算选中的商品总数
    const countTotal = computed(() => {
        if (allItemsSelected) {
            let sumCount = 0;
            suppliers.value.forEach(supplier => {
                supplier.items.forEach(item => {
                    if (item.selected) {
                        sumCount += item.g_count;
                    }
                });
            })
            return sumCount;
        } else {
            return suppliers.value.reduce((g_count, supplier) => g_count + supplier.g_count, 0);
        }
    });
    // 更新所有总金额
    const updateTotals = () => {
        suppliers.value.forEach(supplier => {
            supplier.items.forEach(item => (item.total = item.g_unitPrice * item.g_count));
        });
    };
    updateTotals();

    // 删除购物车项
    const deleteCartItem = (g_id, g_name) => {
        //提示用户  确认框
        ElMessageBox.confirm(
            '你确认要从购物车中删除' + g_name + '吗?',
            '温馨提示',
            {
                confirmButtonText: '确认',
                cancelButtonText: '取消',
                type: 'warning',
            }
        ).then(async () => {
            let result = await cartDeleteService(g_id);
            console.log('g_id为：')
            console.log(g_id)
            if (result.code === 0) {
                ElMessage.success("删除成功")
                location.reload();
            } else {
                ElMessage.error("删除失败")
            }
        })
    }
    // 结算弹窗
    const showModal = ref(false);

    // 打开结算模态框
    function handleCheckout() {
        let params = {
            time: '',
            state: 0,
            shoppingCartOrderItems: [{
                goodsId: 0,
                goodsUnitPrice: 0,
                goodsAmount: 0
            }]
        }
        params.shoppingCartOrderItems.length = 0
        const flag = ref(false)
        suppliers.value.forEach(supplier => {
            supplier.items.forEach(item => {
                if (item.selected) {
                    if (Number.isInteger(item.g_count) && item.g_count >= 1 && item.g_count <= 99) {
                        //加入订单
                        OrderGoods.push(item);
                        let orderItem = {
                            goodsId: item.g_id,
                            goodsUnitPrice: item.g_unitPrice,
                            goodsCount: item.g_count,
                            orderItemAmount: item.g_unitPrice * item.g_count
                        }
                        params.shoppingCartOrderItems.push(orderItem)
                    } else {
                        flag.value = true;
                    }
                }
            });
        })
        if (flag.value === true) {
        } else if (OrderGoods.length === 0) {
            alert('您还没有选择商品！')
        } else {// 显示弹窗
            params.time = new Date()
            request.post("/t-order/addNewOrderFromShoppingCart", JSON.stringify(params), {
                headers: {
                    'Content-Type': 'application/json'
                }
            }).then((resp) => {
                console.log(resp.data)
            })
            showModal.value = true;
        }
    }

    // 关闭结算模态框
    function closeModal() {
        showModal.value = false;
        OrderGoods.splice(0, OrderGoods.length); //清空订单
        suppliers.value.forEach(supplier => {
            supplier.allItemsSelected = false;
            supplier.items.forEach(item => {
                item.selected = false;//清空checkbox
            });
        })
        location.reload();
    }

    //数量变换-更新购物车项
    const handleChange = async (item) => {
        if (Number.isInteger(item.g_count) && item.g_count >= 1 && item.g_count <= 99) {
            let result = await cartUpdateService(item)
            ElMessage.success(result.msg ? result.msg : "修改成功")
            location.reload();
        } else {
            ElMessage.error("请输入1到99之间的整数")
        }
    }

</script>
<template>
    <div class="group-cart">
        <div class="shopping-cart-head">
            <div class="checkbox-wrapper">
                <input type="checkbox" class="cart-checkbox" @click="toggleAllItems" v-model="allItemsSelected"/>
            </div>
            <div class="cartCheck-head">商品信息</div>
            <div class="price-number-container">
                <div class="price-head">单价（/元）</div>
                <div class="number-head">数量</div>
            </div>
        </div>
        <div class="shopping-cart">
            <table v-for="(supplier,supplierIndex) in suppliers" :key="supplierIndex"
                   class="cart-table">
                <tbody>
                <!--                店铺-->
                <tr>
                    <th style="width:2vw;">
                        <input type="checkbox" @change="selectAllSupplierItems(supplier)"
                               :checked="supplier.allItemsSelected" class="cart-checkbox"/>
                    </th>
                    <td style="padding-left: 1vw">{{ supplier.s_username }}</td>
                </tr>
                <!--                    店铺中的商品-->
                <tr v-for="(item,itemIndex) in supplier.items" :key="`${supplierIndex}-${itemIndex}`"
                    style="height: 10vh;">
                    <td>
                        <input type="checkbox" @change="updateItemSelection(supplier,item)" :checked="item.selected"
                               class="cart-checkbox"/>
                    </td>
                    <td class="cart-img-out">
                        <el-image :src="item.g_img" v-if="item.g_img" class="cart-img-class"></el-image>
                        <el-image :src="require(`@/assets/空2.png`)"
                                  class="cart-img-class" v-else></el-image>
                    </td>
                    <td class="nameAndDelete">
                        <span :title="item.g_details">{{ item.g_name }}</span>
                    </td>
                    <td style="border-top: 1px solid black">
                        <el-button type="danger" :icon="Delete" circle @click="deleteCartItem(item.g_id,item.g_name)"
                                   style="background-color: rgba(255,120,214,0.68); width: 3vw; height: 3vw; margin-left: 2vw"/>
                    </td>
                    <td class="cart-price">
                        <span>{{ item.g_unitPrice }}</span>
                    </td>
                    <td class="cart-number-out">
                        <el-input-number v-model="item.g_count" :min="1" :max="99" @change="handleChange(item)"/>
                    </td>
                </tr>
                <tr>
                    <td colspan="6" class="small-settle">
                        金额小计<span class="small-settle-price">{{
                            (calculateSupplierTotal(supplier)).toFixed(2)
                        }}</span></td>
                </tr>
                </tbody>
                <tfoot>
                </tfoot>
            </table>
        </div>
    </div>

    <div v-if="showModal" class="modal">
        <div style="background-color: #b8e3df; margin-bottom: 20px; display: block; padding: 10px">您选择的商品为：</div>
        <div>
            <ul>
                <li v-for="(OrderGood,index) in OrderGoods" :key="index">
                    <h3>{{ OrderGood.g_name }}数量为{{ OrderGood.g_count }}</h3>
                </li>
            </ul>
        </div>
        <div style="justify-content: center; justify-items: center; margin-bottom: 30px">
            <el-button @click="closeModal"
                       style="background-color: lightpink; height: 40px; width: 80px; align-content: center; margin-left: 20vw">
                关闭
            </el-button>
        </div>
    </div>
    <el-drawer>
        这是商品详情
    </el-drawer>
    <div style="position: fixed; bottom: 0; height: 8vh;width: 95vw; background-color: rgba(255,200,234,0.68)">
        <div style=" height: 8vh; line-height: 8vh; position: fixed; left: 4vw; padding-left: 2vw; padding-right: 20vw; color: black; ">
            商品总数量为({{ countTotal }}/{{ countCart }})
        </div>
        <div style=" height: 8vh; line-height: 8vh; position: fixed; right: 4vw; padding-left: 2vw; padding-right: 20vw; color: black; ">
            总金额为{{ (grandTotal).toFixed(2) }}
        </div>
        <button class="finalSettle" @click="handleCheckout">
            去结算
        </button>
    </div>
</template>

<script>
    import {Shop, Delete} from "@element-plus/icons-vue";

    export default {
        name: "ShoppingCart",
        components: {Shop, Delete}
    }
</script>


<style scoped>
    .group-cart {
        /*margin-top: 0;*/
        /*background-color: #FFC0CA;*/
        height: 80vh;
    }

    .shopping-cart-head {
        /*width: 90vw;*/
        width: 96vw;
        height: 3.4vw;
        display: inline-block;
        justify-content: space-between;
        font-size: 11px;
        background-color: white;
        margin-left: 2vw;
        margin-right: 2vw;
    }

    .checkbox-wrapper {
        width: 3vw;
        height: 3vw;
        /*margin: 10px;*/
        border: 1px solid silver;
        display: inline-block;
        justify-content: center;
        align-items: center;
        /*background-color: #FFC0CA;*/
    }

    .cart-checkbox {
        width: 2vw;
        height: 2vw;
    }

    /*购物车头-商品信息*/
    .cartCheck-head {
        display: inline-block;
        /*margin-left: 2vw;*/
        text-align: center;
        /*padding-left: 20vw;*/
        width: 45vw;
    }

    /*价格与数量外容器样式*/
    .price-number-container {
        display: inline-block;
        width: 40vw;
    }

    .price-head {
        display: inline-block;
        width: 20vw;
        text-align: center;
    }

    .number-head {
        display: inline-block;
        width: 18vw;
        text-align: center;
    }

    /*以下为每组购物车项*/
    .shopping-cart {
        /*width: 90vw;*/
        width: 96vw;
        height: 68vh;
        display: inline-block;
        justify-content: space-between;
        font-size: 11px;
        background-color: white;
        margin-left: 2vw;
        margin-right: 2vw;
        /*margin-top: 3vh;*/
        /*margin-top: 1vh;*/
        overflow-y: scroll;
    }

    /*购物车表样式*/
    .cart-table {
        background-color: rgba(255, 230, 246, 0.68);
        border: 1px solid lightgray;
        display: inline-block;
    }

    /*商品名称和删除按钮外样式*/
    .nameAndDelete {
        width: 25vw;
        /*background-color: #57d1e6;*/
        margin-left: 2vw;
        padding-left: 2vw;
        border-top: 1px solid black;
    }

    /*商品图片外样式*/
    .cart-img-out {
        /*background-color: #8c939d;*/
        padding-left: 3vw;
        /*padding-left: 2vw;*/
        /*border-top: 1px solid black;*/
        width: 12vw;
    }

    /*商品图片样式*/
    .cart-img-class {
        width: 6vw;
        height: 6vw;
        margin: 0 auto;
    }

    /*表格中单价样式*/
    .cart-price {
        /*background-color: darkorange;*/
        width: 20vw;
        text-align: center;
        border-top: 1px solid black;
    }

    /*删除按钮样式*/
    .delete-cart-goods {
        color: rgba(87, 86, 89, 0.68);
        background-color: whitesmoke;
        margin-left: 2vw;
    }

    /*商品数量外样式*/
    .cart-number-out {
        width: 25vw;
        /*background-color: #b8e3df;*/
        display: flex;
        justify-content: center;
        padding: 1.4vw;
        border-top: 1px solid black;
    }

    /*减少商品数量样式*/
    .number-minus {
        width: 3vw;
        height: 3vw;
        display: inline-block;
    }

    /*商品数量样式*/
    .cart-number {
        display: inline-block;
        width: 3vw;
        height: 3vw;
        background-color: white;
        text-align: center;
        align-content: center;
        border: 1px solid black;
    }

    /*增加商品数量样式*/
    .number-add {
        width: 3vw;
        height: 3vw;
        display: inline-block;
    }

    /*金额小计样式*/
    .small-settle {
        background-color: rgba(255, 176, 218, 0.68);
        height: 8vh;
        text-align: right;
        padding-right: 20px;
    }

    /*金额小计价格样式*/
    .small-settle-price {
        margin-left: 10px;
    }

    /*结算按钮样式*/
    .finalSettle {
        height: 8vh;
        line-height: 8vh;
        position: fixed;
        right: 4vw;
        padding-left: 2vw;
        padding-right: 2vw;
        color: white;
        background-color: #f10160;
        font-size: 12px
    }

    /*结算弹窗*/
    .modal {
        /* 弹窗样式 */
        position: fixed;
        top: 20vh;
        left: 20vw;
        width: 50%;
        height: 200px;
        overflow-y: auto;
        background-color: white;
        display: block;
        align-items: center;
        justify-content: center;
    }

    .modal ul {
        /* 列表样式 */
        /*background-color: red;*/
        margin-left: 20px;
        padding-left: 20px;
        font-size: 15px;
        display: block;
        margin-bottom: 20px;
    }
</style>
